<?php

namespace App\Jobs;

use Carbon\Carbon;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Support\Facades\Log;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Contracts\Queue\ShouldBeUnique;

class CountTodayBonusJob implements ShouldQueue
{
	use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
	
	public $user;
	
	public function __construct(User $user)
	{
		$this->user = $user;
	}
	
	public function handle()
	{
		$todayBonus = $this->user->goldCoins()
			->whereDate('created_at', Carbon::today())
			->where(function (Builder $query) {
				$query->where('remark', 'resold_profit_coins')
					->orWhere('remark', 'gold_record_direct_prize')
					->orWhere('remark', 'gold_record_team_prize')
					->orWhere('remark', 'prize_exceptional_return'); // remove later
			})->sum('money');
		
		if ($todayBonus <= 0) {
			$todayBonus = 0;
		};
		
		$this->user->update(['dividend_day' => $todayBonus]);
		
		Log::debug("========== User: {$this->user->id} today bonus: $todayBonus");
	}
}
